/*
* created by Administrator on 2018/12/13
* 好的代码像粥一样,是得用时间和精力熬的。
*/
const models = require('../database/model');
const qyerystring = require('querystring');
const axios = require('axios');
const Router = require('koa-router');
const router = new Router();

router.get('/getCode', async (ctx,next) => {
    let {tell} = ctx.request.query;
    let userData = null;
        await models.User.find({phoneNumber: tell})
            .then((data) => {
                userData = data
            })
            .catch(error => {
                ctx.body = {
                    msg: error
                }
            });
        if (userData.length === 0) {
            if (tell && /^1[35789]\d{9}$/.test(tell)){
                function random() {
                    return parseInt(Math.random()*1000000) + '';
                }
                let randomCode = random();
                ctx.session.user = {
                    tell: tell,
                    code: randomCode
                };
                console.log(ctx.session.user);
                let querydata = qyerystring.stringify({
                    mobile: tell,
                    tpl_id: 117434,
                    tpl_value: '#code#='+randomCode,
                    key: 'c686143464757f4a5f6d2d7b933b7bda'
                });
                let url = `http://v.juhe.cn/sms/send?${querydata}`;
                await axios.post(url).then((data) => {
                    console.log(data.data);
                    ctx.body = {
                        code: 1,
                        msg: '发送成功',
                        data: data.data
                    }
                }).catch((error) => {
                    console.log(error);
                    console.log(2);
                    ctx.body = {
                        code: -1,
                        msg: '发送失败',
                    }
                });
            } else {
                ctx.body = {
                    code: -1,
                    msg: '请输入正确的手机号！'
                }
            }
        } else {
            ctx.body = {
                code: -1,
                msg: '该账号已注册！'
            }
        }

    await next();
});
router.get('/register', async (ctx, next) => {
    let {code, password} = ctx.request.query;
    console.log(password);
    if (code && password) {
        if (code === ctx.session.user.code) {
            if (5 < password.length && password.length < 13) {
                let userData = [{
                    phoneNumber: ctx.session.user.tell,
                    code: ctx.session.user.code,
                    password: password,
                }];
                await models.User.insertMany(userData[0])
                    .then(data => {
                        console.log(data);
                        ctx.body = {
                            code: 1,
                            msg: '注册成功!',
                            data
                        }
                    })
                    .catch(error => {
                        ctx.body = {
                            code: -3,
                            msg: '注册失败！',
                            error
                        }
                    });
            } else {
                ctx.body = {
                    code: -2,
                    msg: '请规范密码长度！'
                }
            }
        } else {
            ctx.body = {
                code: -1,
                msg: '验证码错误！'
            }
        }
    } else {
        ctx.body = {
            code: -1,
            msg: '请完善信息'
        }
    }

    await next();
});
router.post('/login', async (ctx, next) => {
    let {tell,password} = ctx.request.body;
    if (tell && password) {
        await models.User.find({phoneNumber: tell},{phoneNumber: 1, password: 1})
            .then(data => {
                if (data[0].phoneNumber === +tell && data[0].password === password) {
                  ctx.body = {
                      code: 1,
                      msg: '登录成功',
                      data
                  }
                } else {
                    ctx.body = {
                        code: -3,
                        msg: '用户名或密码错误',
                        data
                    }
                }
            })
            .catch(error => {
                ctx.body = {
                    code: -2,
                    msg: '账户不存在',
                    error
                }
            })
    } else {
        ctx.body = {
            code: -1,
            msg: '用户名或密码不能为空'
        }
    }
    next();
});
router.get('/resetPasswordGetCode', async (ctx, next) => {
    let {tell} = ctx.request.query;
    let resetPasswordData = null;
    if (tell && /^1[35789]\d{9}$/.test(tell)) {
        await models.User.find({phoneNumber: tell})
            .then(data => {
                resetPasswordData = data;
            })
            .catch(error => {
                ctx.body = {
                    code: -100,
                    msg: '出现无法预料的问题',
                    error
                }
            });
        if (resetPasswordData.length === 0) {
            ctx.body = {
                code: -1,
                msg: '该账号还没有注册'
            }
        } else {
                function random() {
                    return parseInt(Math.random()*1000000) + '';
                }
                let randomCode = random();
                ctx.session.user = {
                    tell: tell,
                    code: randomCode
                };
                console.log(ctx.session.user);
                let querydata = qyerystring.stringify({
                    mobile: tell,
                    tpl_id: 117434,
                    tpl_value: '#code#='+randomCode,
                    key: 'c686143464757f4a5f6d2d7b933b7bda'
                });
                let url = `http://v.juhe.cn/sms/send?${querydata}`;
                await axios.post(url).then((data) => {
                    ctx.body = {
                        code: 1,
                        msg: '发送成功',
                        data: data.data
                    }
                }).catch(() => {
                    ctx.body = {
                        code: -1,
                        msg: '发送失败',
                    }
                });
        }
    } else {
        ctx.body = {
            code: -1,
            msg: '请填写正确的手机号'
        }
    }

    await next();
});
router.get('/resetPassword', async (ctx, next) => {
    let {password, code} = ctx.request.query;
    if (code && password){
        if (code === ctx.session.user.code) {
            if (password.length > 5 && password.length < 13) {
                await models.User.update({phoneNumber: ctx.session.user.tell}, {password,code},)
                    .then(() => {
                        ctx.body = {
                            code: 1,
                            msg: '修改成功'
                        }
                    })
                    .catch(error => {
                        ctx.body = {
                            code: -100,
                            msg: '出现不可预料的错误',
                            error
                        }
                    })
            } else {
                ctx.body = {
                    code: -1,
                    msg: '请规范密码长度'
                }
            }
        } else {
            ctx.body = {
                code: -1,
                msg: '验证码错误'
            }
        }
    } else {
        ctx.body = {
            code: -1,
            msg: '请完善信息'
        }
    }
    await next();
});
router.get('/customerAddress', async (ctx, next) => {
    let customerAddress = ctx.request.query;
    // console.log(customerAddress.id);
    let chart = {
        name: customerAddress.name,
        tell: customerAddress.tell,
        city: customerAddress.city,
        deta: customerAddress.deta
    };
    let _uid = null;
    await models.User.find({phoneNumber: +customerAddress.loginTell}, function (a, b) {
            for(let i = 0;  i < b[0].customerAddress.length; i ++) {
                if (b[0].customerAddress[i]._id  == customerAddress.id) {
                    console.log('chunzai');
                    console.log(customerAddress.name);
                    b[0].customerAddress[i].name  = customerAddress.name;
                    b[0].customerAddress[i].tell  = customerAddress.tell;
                    b[0].customerAddress[i].city  = customerAddress.city;
                    b[0].customerAddress[i].deta  = customerAddress.deta;
                    b[0].markModified('name');
                    b[0].markModified('tell');
                    b[0].markModified('city');
                    b[0].markModified('deta');
                    b[0].save();
                    // console.log('修改成功');
                    console.log(b[0].customerAddress[i]);
                }
            }
    })
        .then(data => {
            if (data[0]) {
                // console.log(data[0].customerAddress);
                _uid = data[0]._id;
                // console.log(_uid)
            } else {
                ctx.body = {
                    code: -10000,
                    msg: '系统异常'
                }
            }
        })
        .catch(error => {
            ctx.body = {
                code: -1000,
                error
            }
        });
    if (!customerAddress.id) {
        console.log('开始加入');
        await models.User.update({_id: _uid},{
            $push: { customerAddress: chart }
        })
            .then(data => {
                console.log(data);
                ctx.body = {
                    code: 1,
                    msg: '增加成功'
                }
            })
            .catch(error => {
                ctx.body = {
                    code: -100,
                    error
                }
            });
    } else {
        ctx.body = {
            code: 2,
            msg: '修改成功'
        }
    }
    next();
});
router.get('/getShippingAddress',async (ctx, next) =>  {
    let {shippingAddress} = ctx.request.query;
    // console.log(shippingAddress);
    await models.User.find({phoneNumber: shippingAddress})
        .then(data => {
            if (data[0]) {
                // console.log(data[0].customerAddress);
                ctx.body = {
                    code: 1,
                    msg: '成功！',
                    data: data[0].customerAddress
                }
            } else {
                ctx.body = {
                    code: -1000,
                    msg: '系统异常',
                }
            }
        })
        .catch(error => {
            ctx.body = {
                code: -1000,
                msg: '系统错误',
                error
            }
        });
    next();
});
router.get('/rmShippingAddress', async (ctx, next) => {
    let data = ctx.request.query;
    console.log(data);
    let uid = null;
    await models.User.find({phoneNumber: data.user})
        .then(data => {
            uid = data[0]._id;
            console.log(data);
        })
        .catch(error => {

        });
    await models.User.update({_id: uid}, { $pull: {customerAddress: { _id: data.id}}})
        .then(data => {
            console.log(data);
            ctx.body = {
                code: 1,
                msg: '删除成功'
            }
        })
        .catch(error => {
            console.log(error);
        });
    next();
});
module.exports = app => app.use(router.routes());
